let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: { 
    disabled_stepper:false,
    query: { //修改订单数据
      goodsId:0,
      optionsId:'',
      orders:[],
      total:1,
      memberCouponIds:[],
      note:''
    },
    orderIds:0,
    levelName:'',
    privacyDesc:'',
    goodsOrder:[],
    TemplateArray:[], //模板ID发送通知
    clickMiniTemplate: false, //判断是否已经点击订阅订单
    goodsDeductions:[], //爱心值积分抵扣系列
    //优惠券
    cup_notice: true,
    coupon_size: 0,
    useCouponSize: 0,
    checkDeductionList: [],
    deduction_lang: '折扣',
    popupCouponSpecs: false,
    checkCouponList: [],
    agreementChecked: false,
    orderShow:false,
    totalPrice:0,
    offlinePrice:'',
    name:'',
    mobile:'',
    pluginSetting:{},
    tagList:[],
    exchange_code_id:"",
    imgPath: app.globalData.imgPath,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.e_id){//兑换码
      this.setData({exchange_code_id:options.e_id,disabled_stepper:true})
    }
    if(options.total){
      this.setData({"query.total":options.total})
    }
    if((options.goodsId??'') !== '') {
      console.log(options.goodsId);
      this.setData({
        'query.goodsId': parseInt(options.goodsId)
      })
      this.orderPay();
      this.preOrderData();
    }
  },
  //组装优惠券json信息
  _assembleCoupons() {
    let coupons = [];
    for (let i = 0; i < this.data.checkCouponList.length; i++) {
      if (this.data.is_coupon_SELE) {
        //开启折叠优惠券
        let conpon_arr = this.data.checkCouponList[i].has_conpon_id;
        coupons = coupons.concat(conpon_arr.slice(0, this.data.coupons_temp[this.data.checkCouponList[i].coupon_id].num));
        this.setData({
          useCouponSize: coupons.length,
        });
      } else {
        coupons.push(this.data.checkCouponList[i].id);
      }
    }
    return coupons;
  },
  //组装json数据
  orderPay() { //预下单
    let that = this;
    let urlStr = app.getNetAddresss("order.goods-buy");
    if(this.data.e_id){
      urlStr = app.getNetAddresss("plugin.exchange-code.api.goods-buy");
    }
    let json = {
      goods_id: this.data.query.goodsId,
      option_id: this.data.query.optionsId,
      total: this.data.query.total,
      dispatch_type_id: 0,
      member_coupon_ids: this._assembleCoupons(),
      orders: JSON.stringify(this._assembleDeduction())
    };
    if(this.data.exchange_code_id){
      urlStr = app.getNetAddresss('plugin.exchange-code.api.goods-buy');
      json.exchange_code_id = this.data.exchange_code_id
    }
    app._postNetWork({
      url: urlStr,
      data:json,
      success: function (resdata) {
        let res = resdata.data;
        if (res.result == 1) {
          console.log(res.data.orders);
          let goodsDeductions = res.data.orders[0]?.order_deductions;
          if(Object.prototype.toString.call(goodsDeductions) === '[object Object]' ) { //判断是对象转化数组格式
            goodsDeductions = Object.values(res.data.orders[0]?.order_deductions)
          }
          let orders = [];
          orders.push({
            pre_id: res.data.orders[0].pre_id
          })
          // that.defaultSelectCoupon(res.data.discount?.member_coupons);
          that._initCoupon(res.data.discount); //设置优惠券信息
          that.setData({
            goodsOrder: res.data.orders,
            totalPrice:  res.data.total_price,
            goodsDeductions: goodsDeductions,
            checkCouponList: res.data.discount?.member_coupons,
            'query.note': res.data.orders[0]?.note,
            'query.orders': orders
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  preOrderData() { //预下单格外数据
    let that = this;
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.order.preOrderData");
    let json = {
      goods_id: this.data.query.goodsId,
      basic_info: 1
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success: function (resdata) {
        let res = resdata.data;
        if (res.result == 1) {
          that.setData({
            levelName: res.data.level_name,
            privacyDesc: res.data.privacy_desc,
            offlinePrice: res.data.offline_price,
            pluginSetting: res.basic_info?.plugin_setting?.coupon_store,
            tagList: res.data.tag_list
          })
          
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //获取模板id
  getTemplate() {
    let urlStr = app.getNetAddresss("member.member.getMiniTemplateCorrespond");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: 1,
        order_id: this.data.orderIds
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let array = [];
          for (let i = 0; i < res.data.length; i++) {
            array.push(res.data[i].template_id);
          }
          that.setData({
            TemplateArray: array,
          });
          if (that.data.TemplateArray.length > 0) {
            wx.requestSubscribeMessage({
              tmplIds: that.data.TemplateArray,
              success(res) {
                that.setData({
                  clickMiniTemplate: true
                });
                wx.redirectTo({
                  url: "../../../packageD/buy/orderPay/orderPay?order_id=" + that.data.orderIds + "&status=2"
                });
              },
              fail(err) {
                console.log(err, "err");
                wx.redirectTo({
                  url: "../../../packageD/buy/orderPay/orderPay?order_id=" + that.data.orderIds + "&status=2"
                });
              },
            });
          } else {
            wx.redirectTo({
              url: "../../../packageD/buy/orderPay/orderPay?order_id=" + that.data.orderIds + "&status=2"
            });
          }
        } else {
          Toast(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  onOrderPay() { //确定下单
    if(app._isTextEmpty(this.data.name)) {
      wx.showToast({
        icon: 'none',
        title: '请输入姓名',
        duration: 1500
      });
      return;
    }
    if(app._isTextEmpty(this.data.mobile)) {
      wx.showToast({
        icon: 'none',
        title: '请输入手机号',
        duration: 1500
      });
      return;
    }
    if(app._isTextEmpty(this.data.agreementChecked)) {
      wx.showToast({
        icon: 'none',
        title: '请同意个人信息保护声明',
        duration: 1500
      });
      return;
    }
    let urlStr = app.getNetAddresss("order.create");//下单接口
    let goods = [];
    let that = this;
    goods.push({
      goods_id: this.data.query.goodsId,
      option_id: this.data.query.optionsId,
      total: this.data.query.total
    })
    let json = {
      dispatch_type_id: 0,
      name:this.data.name,
      mobile: this.data.mobile,
      member_coupon_ids: this._assembleCoupons(),
      goods: JSON.stringify(goods),
      orders: JSON.stringify(this._assembleDeduction())
    };
    if(this.data.exchange_code_id){
      json.exchange_code_id = this.data.exchange_code_id;
      urlStr =app.getNetAddresss("plugin.coupon-store.frontend.create.index");
    }
    app._postNetWork({
      url: urlStr,
      data:json,
      success: function (resdata) {
        let res = resdata.data;
        if (res.result == 1) {
          
          that.setData({
            orderIds: res.data.order_ids
          })
          if (that.data.clickMiniTemplate) { //判断是否同意消息通知
            wx.showLoading({
              title: "加载中",
            });
            wx.redirectTo({
              url: "../../../packageD/buy/orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2"
            });
          } else {
            that.getTemplate();
          }
          
          return
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onOrderSubmit() {
    this.onOrderPay();
  },
  onTotalChange(event) { //修改数量
    this.setData({
      'query.total': event.detail
    })
    this.orderPay();
  },
  onAgreementChange(event) {
    this.setData({
      agreementChecked: event.detail,
    });
  },
  //初始化优惠券
  _initCoupon(data) {
    if (data.deduction_lang) {
      this.setData({
        deduction_lang: data.deduction_lang
      });
    }
    this.setData({
      isShowCoupon: data.whether_show_coupon == "1" ? true : false,
    });
    let coupon = data.member_coupons;
    this.setData({
      is_coupon_SELE: data.coupon_show == "1" ? true : false,
    });
  
    this.setData({
      coupon_size: coupon.length,
    });
    if (coupon != undefined && coupon != "" && coupon != null) {
      if (this.data.is_coupon_SELE) {
        //按过期时间排序
        let arr2 = coupon.sort((a, b) => {
          return a.expired_at - b.expired_at;
        });
        this.initSelectCoupon(arr2);
      } else {
        this.setData({
          coupons: coupon,
        });
      }
    }
  },
  //初始化带有默认选中优惠券
  defaultSelectCoupon(coupon) {
    let checkCouponList = [];
    coupon.forEach((item, ind) => {
      if (item.checked == true) {
        checkCouponList.push(item);
      }
    });
    this.setData({
      coupon_size: coupon.length,
      coupons: coupon,
      useCouponSize: checkCouponList.length,
      checkCouponList: checkCouponList,
    });
  },
  //折叠优惠券
  initSelectCoupon(coupon) {
    let coupon_data = coupon;
    let result = [];
    let temp = {};
    for (let i = 0; i < coupon_data.length; i++) {
      let num = 0; //同类型已选中并符合使用条件的优惠券数量
      let valid = 0; //最高限制使用数量
      let has_conpon_id = [coupon_data[i].id];
      if (coupon_data[i].checked) {
        console.log(coupon_data[i].checked);
        num++;
      }
      if (coupon_data[i].valid) {
        console.log(coupon_data[i].valid);
        valid++;
      }
      for (let j = i + 1; j < coupon_data.length; j++) {
        // console.log("33333333==================", coupon_data[j].coupon_id)
        if (coupon_data[i].coupon_id == coupon_data[j].coupon_id) {
          if (coupon_data[j].checked) {
            num++;
          }
          if (coupon_data[j].valid) {
            valid++;
          }
          has_conpon_id.push(coupon_data[j].id);
          coupon_data.splice(j, 1);
          j--;
        }
      }
      let _data = coupon_data[i];
      _data.has_conpon_id = has_conpon_id;
      _data.valid_num = valid;
      result.push(_data);
      temp[coupon_data[i].coupon_id] = {};
      temp[coupon_data[i].coupon_id].num = num;
    }

    this.setData({
      coupons_temp: temp,
      coupons: result,
    });
  },
  //优惠券
  showCoupon() {
    if (this.data.coupon_size == 0) {
      wx.showToast({
        icon: "none",
        title: "暂无优惠券使用",
        duration: 1500,
      });
      return;
    }
    this.setData({
      popupCouponSpecs: true,
    });
  },
  //选择优惠券
  selectCoupon(e) {
    let couponBol = e.detail;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    // let ids = [];
    
    // console.log(ids);
    // this.setData({
    //   ["coupons[" + index + "].checked"]: couponBol,
    // });
    // for(let i in this.data.coupons) {
    //   if(this.data.coupons[i].checked) {
    //     console.log(this.data.coupons[i]);
    //     ids.push(this.data.coupons[i].id);
    //   }
    // }
    // this.setData({
    //   memberCouponIds: ids,
    //   useCouponSize: ids.length
    // });

    this.setData({
      ["coupons[" + index + "].checked"]: couponBol,
    });
    this._screenCoupon(couponBol, item, e.type);
    //设置view
    this._setCouponView();
    //重新计算
    this.orderPay();
  },
  //设置view
  _setCouponView() {
    this.setData({
      useCouponSize: this.data.checkCouponList.length,
      
    });
  },
  //筛选数据优惠券状态
  _screenCoupon(couponBol, valObj, type) {
    let tarValue = valObj;
    let checkCouponList = this.data.checkCouponList;
    if (this.data.checkCouponList.length > 0) {
      for (let i = 0; i < this.data.checkCouponList.length; i++) {
        if (this.data.checkCouponList[i].id == tarValue.id) {
          checkCouponList.splice(i, 1);
        }
      }
    }
    if (this.data.is_coupon_SELE && type) {
      //开启折叠优惠券并且为点击复选框为选中状态
      this.data.coupons_temp[tarValue.coupon_id].num = couponBol ? 1 : 0;
      this.setData({
        coupons_temp: this.data.coupons_temp
      });
    }
    if (couponBol) {
      //选中添加
      checkCouponList.push(tarValue);
    } else {
      //取消选中
      this.setData({
        cup_notice: true
      });
    }
    
    this.setData({
      checkCouponList: checkCouponList
    });
  },
   //关闭优惠卷
  couponclose() {
    this.setData({
      popupCouponSpecs: false,
    });
  },
  mustSelectCoupon() {
    // 后台设置，下单前判断有优惠券数量但没使用时，是否提示并展开选择优惠券弹窗，只提示一次！
    if (this.data.openCueCoupon && this.data.coupon_size > 0 && this.data.useCouponSize < 1 && !this.data.isCueCoupon) {
      //显示优惠券列表弹窗
      // 按钮文字改变
      this.setData({
        isCueCoupon: true,
        popupCouponSpecs: true,
      });
      return true;
    }
    return false;
  },
  changeConpon(e) {
    let valObj = e.target.dataset.item;
    let num = e.detail;
    let index = e.target.dataset.index;
    if (num > valObj.valid_num) {
      wx.showToast({
        icon: "none",
        title: "使用张数已达上限",
        duration: 1000,
      });
      clearTimeout(this.data.timer);
      this.data.timer = setTimeout(() => {
        // 注意此时修改 value 后会再次触发 change 事件
        this.data.coupons_temp[valObj.coupon_id].num = valObj.valid_num;
        this.setData({
          coupons_temp: this.data.coupons_temp,
        });
      }, 200);
      return;
    } else if (num == "" || num == undefined || num == 0) {
      wx.showToast({
        icon: "none",
        title: "暂不使用请取消勾选",
        duration: 1000,
      });
      return;
    } else {
      clearTimeout(this.data.timer);
      this.data.coupons_temp[valObj.coupon_id].num = num;
      this.setData({
        coupons_temp: this.data.coupons_temp,
      });
    }

    // clearTimeout方法，以便控制连续触发带来的无用调用
    let value = {
      detail: true,
      currentTarget: {
        dataset: {
          index: index,
          item: valObj,
        },
      },
    };
    if (this.data.timeoutId) {
      clearTimeout(this.data.timeoutId); // 先清除之前的延时，并在下面重新开始计算时间
    }
    this.data.timeoutId = setTimeout(() => {
      // 100毫秒以后执行方法
      this.selectCoupon(value);
    }, 1000); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
  },
  onLikeChange(event) {
    let goodsDeductions = this.data.goodsDeductions;
    let index = event.currentTarget.dataset.index;
    goodsDeductions[index].checked = event.detail;
    // 需要手动对 checked 状态进行更新
    this.setData({ 
      goodsDeductions: goodsDeductions
    });
    this._assembleDeduction();
    this.orderPay();
  },
  _assembleDeduction(data) { //修改提交的orders数据
    let deductions = [];
    let DeductionsData = [];
    let DeductionsId = [];
    let goodsDeductions = this.data.goodsDeductions;
    let newObj = {};
    DeductionsData = goodsDeductions.filter((item) => { //筛选选中的爱心值，积分等等
      return item.checked === true
    })
    DeductionsData.forEach((item) => {  //获取code值
      DeductionsId.push(item.code);
    })
    this.data.query.orders.push({
      deduction_ids: DeductionsId,
      note: this.data.query.note
    })
    this.data.query.orders.forEach((item) => {
      if(item) {
        newObj = { ...newObj, ...item }  // 要把自己放进去
      }
    })
    if(Array.prototype.isPrototypeOf(this.data.query.orders) && this.data.query.orders.length !== 0) { //不是空数组的时候才添加对象
      deductions.push(newObj)
    }
    return deductions;
  },
  modelInput(event) { //监听输入框的值
    const item = event.currentTarget.dataset.item,
          itemValue = event.detail.value;
    this.setData({
      [item]:itemValue
    })
  },
  onClose() {
    this.setData({
      orderShow: false
    });
  },
  onAgreement() {
    this.setData({
      orderShow: true
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})